package com.example.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.vo.DataView;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;


    @RequestMapping("/login/getCode")
    public void getCode(HttpServletResponse response, HttpSession session){
        //HuTool定义图形验证码的长和宽,验证码的位数，干扰线的条数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36,4,10);
        session.setAttribute("code",lineCaptcha.getCode());
        System.out.println("code:"+lineCaptcha.getCode());
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            lineCaptcha.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/login/login")
    @ResponseBody
    public DataView login(String username,String password,String code,HttpSession session){
        DataView dataView = new DataView();

        //判断验证码对不对
        String sessionCode = (String) session.getAttribute("code");
        if (code != null && sessionCode.equals(code)){

            User user=null;
            try{
                Subject subject = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                subject.login(token);
                user = (User) subject.getPrincipal();
                if(user != null){
                    dataView.setCode(200);
                    dataView.setMsg("登录成功");
                    session.setAttribute("user",user);
                }else{
                    dataView.setCode(100);
                    dataView.setMsg("用户名或者密码错误，登录失败");
                }
            }catch (Exception e){
                dataView.setCode(100);
                dataView.setMsg("用户名或者密码错误，登录失败");
            }
        }else{
            dataView.setCode(100);
            dataView.setMsg("验证码错误，登录失败");
        }
        return dataView;
    }

    @RequestMapping("/login/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }



}
